#文本处理函数，为了之后方便计数
def word():
    global lst
    global word_list
    lst = []
    word_list = []
    with open("Walden.txt", "r+", encoding="utf-8") as fp:
        import re
        a = fp.read()
        # 将大写转换为小写
        lower_word = a.lower()
        # 替换文中的特殊字符
        b = re.sub(r'[\d",\n/?+:.;$-]', ' ', lower_word)
        c = b.split(" ")

        for i in c:
            # 去空格，单词存进列表
            if i == '' or i == '--':
                pass
            else:
                lst.append(i)

        word_list = lst.copy()

word()

#计数函数
def count():
    global dict_words
    global count_words
    count_words = 0
    dict_words = {}
    # 计数每个单词出现次数，并存入dict_words字典
    for i in word_list:
        count_words = word_list.count(i)
        dict1 = {i: count_words}
        dict_words.update(dict1)
    # 输出结果
    print(dict_words)

count()
